/**
 * Created by ztq on 2015/11/24.
 */
var IUserService = require('../api/service').IUserService
var utils = require('utility')
var helper = require('./helper')
var Menu = require('../domain/domain').Menu
var User = require('../domain/domain').User
var Recipe = require('../domain/domain').Recipe
var Message = require('../domain/domain').Message

module.exports = function (app) {
    //---------菜单模块首页：最近流行菜单----只有一页，10条数据--：：：最近30天点赞数跟收藏数的平均数前10名
    app.get("/menu/popularMenus", function *() {
        var $self = this
        console.log("menu main: ")
        var user = $self.session.user
        var menus = yield $self.db('SELECT *,m.recipeCount as recipeCount ,(m.upvote + m.collectionCount)/2 as d FROM Menu m,Recipe_Menu rm,Recipe r,User u WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= m.createOn AND m.id = rm.m_id AND u.id = m.user_id  AND rm.r_id = r.id GROUP BY m.name ORDER BY d DESC LIMIT 10').list()
        yield $self.render("/menu/menu", {
            title:'最近流行',
            menus:menus,
            login_user:user
        })
    })

    //-------------获取往期头条菜单----分页，每页15条------
    app.get('/menu/lastMenus/page/:pageNum',function*(){
        var $self = this
        var user = $self.session.user
        var contentCount = 10
        var a = $self.params.pageNum
        console.log("type is " + typeof(a) + " value is " + a)
        var pageNum = (parseInt($self.params.pageNum) - 1) * contentCount
        //var menus = yield $self.db('SELECT *,m2.createOn as createOn,DATE_FORMAT( m2.createOn, "%Y-%m-%d" ) as date FROM (SELECT *,(m.upvote + m.collectionCount)/2 as d FROM Menu m ORDER BY d DESC ) m2,User u WHERE u.id = m2.user_id GROUP BY date ORDER BY date DESC LIMIT ?,?',[page,contentCount]).execute()
        var sqls = []
        sqls.push('SELECT *,r.id as rid FROM')
        sqls.push('(SELECT m2.name as mname,m2.id as mid,m2.recipeCount as mrecipeCount,m2.createOn as mcreateOn,m2.collectionCount as mcollectionCount,m2.user_id as muser_id,u.id as uid,u.nick as unick ,DATE_FORMAT( m2.createOn, "%Y-%m-%d" ) as date')
        sqls.push('FROM (SELECT *,(m.upvote + m.collectionCount)/2 as d FROM Menu m ORDER BY d DESC ) m2,User u')
        sqls.push('WHERE u.id = m2.user_id GROUP BY date ORDER BY date DESC LIMIT ?,?) m3,Recipe_Menu rm,Recipe r')
        sqls.push('WHERE m3.mid = rm.m_id AND rm.r_id = r.id GROUP BY m3.mid ORDER BY m3.mcreateOn DESC')
        var menus = yield $self.db(sqls.join(' '),[pageNum,contentCount]).list()
        for(var key in menus)
        {
            console.log('-----往期头条菜单menus['+key+']----->>'+menus[key].mname)
            console.log('----->>'+menus[key].mcreateOn)
        }
        yield $self._render('/menu/lastMenus',{
            title:'往期头条',
            menus:menus,
            dateformat: utils.YYYYMMDD
        })
    })

    //-------------获取月度最佳菜单-------按时间：年月 ----
    app.get('/menu/monthlyMenus/:time',function *(){
        var $self=this
        var user = $self.session.user
        var time = $self.params.time
        console.log('--time-->>'+time)
        var sqls = []
        sqls.push('SELECT *,r.id as rid,(m3.upvote + m3.collectionCount)/2 as d FROM')
        sqls.push('(SELECT upvote,collectionCount, m2.name as mname,m2.id as mid,m2.recipeCount as mrecipeCount,m2.createOn as mcreateOn,m2.collectionCount as mcollectionCount,m2.user_id as muser_id,u.id as uid,u.nick as unick ,DATE_FORMAT( m2.createOn, "%Y-%m-%d" ) as date ')
        sqls.push('FROM (SELECT *,(m.upvote + m.collectionCount)/2 as d FROM Menu m WHERE DATE_FORMAT(createOn,"%Y%m")= ? ORDER BY d DESC LIMIT 0,10) m2,User u ')
        sqls.push('WHERE u.id = m2.user_id GROUP BY date ORDER BY date DESC ) m3,Recipe_Menu rm,Recipe r')
        sqls.push('WHERE m3.mid = rm.m_id AND rm.r_id = r.id GROUP BY m3.mid  ORDER BY d DESC')
        var menus = yield $self.db(sqls.join(' '),time).list()
        for(var key in menus)
        {
            console.log('-----往期头条菜单menus['+key+']----->>'+menus[key].mname)
            console.log('----->>'+menus[key].mcreateOn)
        }
        yield $self.render('/menu/bestMenu',{
            title:'月度最佳',
            login_user:user,
            menus:menus
        })
    })

    //-------------获取厨房101菜单-----分页，每页10条------
    app.get('/menu/top101/page/:pageNum',function *(){
        var $self=this
        //$self.query.pageNum;
        var user = $self.session.user
        var contentCount = 10
        var pageNum = (parseInt($self.params.pageNum) - 1) * contentCount
        var sqls=[]
        sqls.push('SELECT *,m2.name as mname,m2.id as mid,m2.recipeCount as mrecipeCount,m2.createOn as mcreateOn FROM')
        sqls.push('(SELECT *,(m.upvote + m.collectionCount)/2 as d FROM Menu m ORDER BY d DESC LIMIT 0,101) m2,User u,Recipe_Menu rm,Recipe r ')
        sqls.push('WHERE m2.id = rm.m_id AND rm.r_id = r.id AND m2.user_id = u.id GROUP BY m2.id ORDER BY m2.d DESC LIMIT ?,?')
        var menus = yield $self.db(sqls.join(' '),[pageNum,contentCount]).list()
        yield $self.render('/menu/menu101',{
            title:'厨房101',
            login_user:user,
            menus:menus,
            dateformat: utils.YYYYMMDD
        })
    })

    //-------------删除菜单-----默认已经登录了-------
    app.get('/menu/deleteMenu/:mid',function *(){
        var $self = this
        var mid = $self.params.mid
        console.log('-----/menu/deleteMenu/:mid------>>' + mid)
        yield $self.db('DELETE FROM Menu WHERE id = ?',mid).execute()
        yield $self.db('DELETE FROM Recipe_Menu WHERE m_id = ?',mid).execute()
        yield $self.db('DELETE FROM Menu_Collecting WHERE m_id = ?',mid).execute()
        yield $self.db('DELETE FROM Menu_Upvote WHERE m_id =?',mid).execute()
        yield $self.db('UPDATE User SET menuCount = menuCount - 1 WHERE id = ?',$self.session.user.id).execute()
        //yield $self.db('DELETE FROM Menu_upvote WHERE m_id = ?',mid).execute()
        //yield $self.db('DELETE FROM Menu_Collecting WHERE m_id = ?',mid).execute()
        $self.response.redirect('/user/'+$self.session.user.nick+'/menu')
    })

    //------------跳转到更新菜单页面
    app.get('/menu/edit/:mid',function*(){
        var $self = this
        var mid = $self.params.mid
        var menu = yield $self.db('SELECT * FROM Menu WHERE id = ?',mid).unique()
        console.log('----menu--->>'+menu.description)
        yield $self.render('/menu/menuEdit',{
            title:'更新菜单',
            login_user:$self.session.user,
            menu:menu
        })
    })

    //-----------更新菜单-------默认已经登录了-------
    app.post('/menu/update/:mid',function *(){
        var $self = this
        var body = $self.request.body
        var mid = $self.params.mid
        yield $self.db("UPDATE Menu SET name =?,description = ? WHERE id = ?",[body.menuName,body.menuDescription,mid]).execute()
        $self.response.redirect('/menu/detail/'+mid)
    })

    /*//----------获取我的菜单-----------
    app.get('/menu/mine',function *(){
        var $self = this
        var mid = $self.session.user.id
        var menus = yield $self.db('SELECT * FROM Menu WHERE user_id = ?',mid).list()
        for(var key in menus){
            console.log('---/menu/mine--->'+menus[key].name)
        }
        yield $self._render('/menu/mine',{menus:menus})
    })*/

    //----------菜单详情--------------
    app.get('/menu/detail/:mid',function*(){
        var $self = this
        var mid = $self.params.mid
        var menu = yield $self.db('SELECT * FROM Menu WHERE id = ?',mid).unique()
        var recipes = yield $self.db('SELECT *,r.id as rid FROM Recipe_Menu rm ,Recipe r,User u WHERE rm.r_id = r.id AND u.id = r.owner_id AND m_id =?',mid).list()//菜单所包含的菜谱
        var resultUser = yield $self.db('SELECT * FROM User WHERE id = ?',menu.user_id).unique()//获取创建该菜单的用户
        var menus = yield $self.db('SELECT *,m.recipeCount as recipeCount ,(m.upvote + m.collectionCount)/2 as d FROM Menu m,Recipe_Menu rm,Recipe r,User u WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= m.createOn AND m.id = rm.m_id AND u.id = m.user_id  AND rm.r_id = r.id GROUP BY m.name ORDER BY d DESC LIMIT 10').list()//最近流行
        console.log('---菜单详情-->>')
        console.log('-----mid--->>'+mid)
        console.log('-----menu.name--->>'+menu.name)
        for(var key in recipes){
            console.log('-----recipes['+key+'].title---->>'+recipes[key].title)
        }
        var user = $self.session.user
        var isMyMenu = 0
        var isCollected = 0
        var isUpvoted = 0
        if(user)//判断创建该菜单的是不是当前登录的用户
        {
            if(user.id == resultUser.id){
                isMyMenu = 1
            }
            var result1 = yield $self.db('SELECT * FROM Menu_Collecting WHERE u_id = ? AND m_id = ?',[user.id,mid]).unique()//判断是否已收藏
            console.log("------>>>result1:"+result1)
            if(!result1)
            {
                isCollected = 0
            }else
            {
                isCollected = 1
            }
            var result2 = yield $self.db('SELECT * FROM Menu_Upvote WHERE u_id = ? AND m_id = ?',[user.id,mid]).unique()//判断是否点过赞
            if(!result2)
            {
                isUpvoted = 0
            }else
            {
                isUpvoted = 1
            }
        }
        console.log("-----isCollected------->>"+isCollected)
        yield $self._render('/menu/menuDetail',{
            title:menu.name,
            menu:menu,
            menus:menus,
            recipes:recipes,
            user:resultUser,
            isCollected:isCollected,
            isUpvoted:isUpvoted,
            isMyMenu:isMyMenu,
            dateformat: utils.YYYYMMDD
        })
    })

    //----------点赞菜单---(限点一次)--------
    app.get('/menu/like/:mid',function *(){
        var $self = this
        var mid = $self.params.mid
        var user = $self.session.user
        console.log('---/menu/like/'+mid)
        if(!user)
        {
            yield $self.render('/login')
        }else
        {
            var uid = user.id
            var mid = $self.params.mid
            var value = {m_id:mid,u_id:uid,createOn:utils.YYYYMMDDHHmmss(new Date().toLocaleString())}
            yield $self.db('INSERT INTO Menu_Upvote SET ?',value).execute()
            yield $self.db('UPDATE Menu SET upvote = upvote + 1 WHERE id = ?',mid).execute()//UPDATE Menu SET upvote = upvote + 1 WHERE id = ?

            //往Message表添加一条数据用于通知用户
            var menu = yield $self.db('SELECT * FROM Menu WHERE id = ?',mid).unique()
            var user = yield $self.db('SELECT * FROM User WHERE id = ?',menu.user_id).unique()
            console.log('--menu--user-->>'+menu.user_id+' ' + user.id)
            var message = new Message()
            message.user_id = uid
            message.another_id = user.id
            message.obj_id = mid
            message.type = Message.TYPE_UPVOTE_MENU
            message.another_already_read = false
            delete message.id
            yield $self.db('INSERT INTO Message SET ?', message).execute()

            $self.response.redirect('/menu/detail/'+mid)
        }
    })

    //----------收藏菜单------------
    app.get('/menu/collect/:mid',function *(){//方式改为post
        console.log('----收藏菜单----->>')
        var $self = this
        var user = $self.session.user
        if(!user)
        {
            yield $self.render('/login')//todo 登录后回到菜单页
        }else
        {
            var uid = user.id
            var mid = $self.params.mid
            var value = {m_id:mid,u_id:uid,createOn:utils.YYYYMMDDHHmmss(new Date().toLocaleString())}
            yield $self.db('INSERT INTO Menu_Collecting SET ?',value).execute()
            // 菜单收藏加1
            yield $self.db('UPDATE Menu SET collectionCount = collectionCount + 1 WHERE id = ?',mid).execute()//UPDATE Menu SET collectionCount = collectionCount + 1 WHERE id = ?
            $self.response. redirect('/menu/detail/'+mid)
        }
    })

    //---------取消收藏菜单-------默认登录了的---
    app.get('/menu/cancelCollect/:mid',function *(){

        var $self = this
        var uid = $self.session.user.id
        var mid = $self.params.mid
        console.log('----取消收藏菜单----->>'+uid +" " +mid)
        yield $self.db('DELETE FROM Menu_Collecting WHERE m_id = ? AND u_id = ?',[mid,uid]).execute()
        // 菜单收藏减1
        yield $self.db('UPDATE Menu SET collectionCount = collectionCount - 1 WHERE id = ?',mid).execute()
        $self.response. redirect('/menu/detail/'+mid)
    })

    ////-----------获取收藏菜单--------
    //app.get('/menu/myCollection',function *(){
    //    var $self = this
    //    var user = $self.session.user
    //    var menus = yield $self.db('SELECT * FROM Menu_Collecting mc,Menu m WHERE mc.m_id = m.id AND mc.u_id = ?',user.id)
    //
    //})

  /*  //-------------往菜单添加菜谱----------
    app.get('/menu/:mid/addRecipe/:rid',function *(){//todo 改为post方式？
        var $self = this
        var rid = $self.params.rid
        var mid = $self.params.mid
        var value = {m_id:mid,u_id:uid}
        yield $self.db('INSERT INTO Recipe_Menu SET ?',value).execute()
        yield $self.db('UPDATE Menu SET recipeCount = recipeCount + 1 WHERE id = ?',mid).execute()
        $self.response.redirect('/recipe/details/'+rid)
    })*/

    //-------------往菜单删除菜谱----------
    app.get('/menu/:mid/deleteRecipe/:rid',function *(){
        var $self = this
        var rid = $self.params.rid
        var mid = $self.params.mid
        yield $self.db('DELETE FROM Recipe_Menu WHERE m_id = ? AND r_id = ?',[mid,rid]).execute()
        yield $self.db('UPDATE Menu SET recipeCount = recipeCount - 1 WHERE id = ?',mid).execute()
        $self.response.redirect('/menu/detail/'+mid)
    })
}